/*
 * @(#)KeyGeneratorMgr.java  2010/11/22
 *
 * Copyright (c) 2010. i2finance., Ltd. All rights reserved.
 */

package com.TTBook.utils.keygen;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.TTBook.core.service.AbstractService;
import com.TTBook.core.system.dao.SerialNoDAO;
import com.TTBook.core.system.model.SerialNo;
import com.TTBook.utils.keygen.adapter.SerialGeneratorDataAdapter;

/**
 * <p>Description:</p>
 *
 * Created Date: 2010-11-22
 * Created time: 14:51:55
 *
 * @author : Frank
 *
 */
public class SerialGeneratorMgr extends AbstractService {
	
    private Map<String, SerailGenerator> sgs = new HashMap<String, SerailGenerator>();
	
	@Autowired
	private SerialNoDAO serialNoDAO = null;

	@Autowired
	private SerialGeneratorDataAdapter serialGeneratorDataAdapter = null;
	
	
	public void setSerialNoDAO(SerialNoDAO serialNoDAO) {
		this.serialNoDAO = serialNoDAO;
	}


	public void setSerialGeneratorDataAdapter(
			SerialGeneratorDataAdapter serialGeneratorDataAdapter) {
		this.serialGeneratorDataAdapter = serialGeneratorDataAdapter;
	}


    
    /**
     * 
     * <b>Method Function Description:</b><br>
     * 根据Serial Name获取序列号
     * @param serialName
     * @return
     * <br><b>Method Logic Description:</b>
     * 1.先根据Serial Name获取对应的KeyGenerator。
     * 2.再调用SerialGenerator的getNextKey获得下一序列号。
     */
    public String getSerialKey(String serialName) {
        if (sgs.containsKey(serialName)) {
        	SerailGenerator sg = (SerailGenerator) sgs.get(serialName);
            return sg.getNextKey();
        } else {
        	SerailGenerator sg = getSerailGenerator(serialName);
        	if(sg==null){
        		throw new IllegalArgumentException("The keygen cannot be null with the key name:"+serialName);
        	}
        	sgs.put(serialName, sg);
        	return sg.getNextKey();
        }
    }
    
    
    private SerailGenerator getSerailGenerator(String serialName){
    	SerialNo serialNo = serialNoDAO.selectByPrimaryKey(serialName);
    	if(serialNo==null){
    		throw new IllegalArgumentException("The serial name "+serialName+" not defined in the DB");
    	}
    	return  new SerailGenerator(serialNo.getSerialPoolSize(),serialNo.getSerialFormat(),serialName,serialGeneratorDataAdapter);
    }
}
